package de.mhus.lib.mandala;

import java.util.HashMap;

import de.mhus.lib.core.activator.DefaultImplementation;
import de.mhus.lib.core.base.IgnoreBind;
import de.mhus.lib.core.lang.Prototype;
import de.mhus.lib.mandala.bind.RemoteCallable;
import de.mhus.lib.mandala.bind.RemoteRegistry;
import de.mhus.lib.mandala.functions.SequenceAction;
import de.mhus.lib.mandala.impl.DefaultWindow;
import de.mhus.lib.mandala.layout.VerticalLayout;

@IgnoreBind
@Prototype
@DefaultImplementation(value=DefaultWindow.class)
public abstract class Window extends VerticalLayout {

	protected Ui ui;
	private long nextId;
	private String id = "model";
	private SequenceAction initialAction;
	private HashMap<String, RemoteRegistry> remoteRegistry = new HashMap<String, RemoteRegistry>();

	public Window() {
	}
	
	public Ui getUi() {
		return ui;
	}
	
	public Window getWindow() {
		return this;
	}

	public String createId() {
		return "a" + nextId++;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public SequenceAction getInitialAction() {
		if (initialAction == null)
			initialAction = new SequenceAction();
		return initialAction;
	}
	
	protected void doRender(Response response) {
		response.registerElement(getInitialAction());
		super.doRender(response);
		response.renderAttributes();
	}
	
	public RemoteRegistry registerRemoteCall(RemoteCallable ds) {
		synchronized (remoteRegistry) {
			RemoteRegistry remote = remoteRegistry.get(ds.getId());
			if (remote == null) {
				remote = new RemoteRegistry(this,ds);
				remoteRegistry.put(ds.getId(), remote);
			}
			return remote;
		}
	}

	public abstract String getRemoteUrl(RemoteRegistry registry);

	public synchronized void close() {
		if (ui == null) return;
		ui.remove(this);
		ui = null;
	}

	public RemoteRegistry getRemote(String id) {
		synchronized (remoteRegistry) {
			return remoteRegistry.get(id);
		}
	}

}
